﻿using Microsoft.ExtendedReflection.ComponentModel;
using Microsoft.ExtendedReflection.Logging;
using Microsoft.ExtendedReflection.Monitoring;
using MolesVS2012.Host;
using System;
using System.Runtime.Remoting;

namespace MolesVS2012.Host.Host
{
    [Serializable]
    internal sealed class MolesHostDriver : ComponentBase, IService
    {
        public int Execute()
        {
            using (_ProtectingThreadContext.Acquire())
            {
                try
                {
                    MolesHostRemotingManager service1 = this.GetService<MolesHostRemotingManager>();
                    if (!service1.TrySetClientReady())
                        return -1002;
                    if (!this.GetService<MolesHostAdapter>().WaitTillRunContextReady())
                        return -1004;
                    this.GetService<RunResultSyncLogger>();
                    MolesHostConsoleLogger service2;
                    this.TryGetService<MolesHostConsoleLogger>(out service2);
                    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(this.UnhandledException);
                    service1.WaitTillFinished();
                    return 0;
                }
                catch (RemotingException ex)
                {
                    return -1006;
                }
                catch (Exception ex)
                {
                    return -1001;
                }
                finally
                {
                    AppDomain.CurrentDomain.UnhandledException -= new UnhandledExceptionEventHandler(this.UnhandledException);
                }
            }
        }

        private void UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            using (_ProtectingThreadContext.Acquire())
            {
                try
                {
                    IEventLog log = this.Log;
                    Exception ex = e.ExceptionObject as Exception;
                    if (ex != null)
                        log.LogErrorFromException(ex, "Missing Wiki Topic", "Host", "An unhandled exception {0} occured while executing the unit tests", new object[1]
            {
              (object) ex.GetType()
            });
                    else
                        log.LogError("Missing Wiki Topic", "Host", "An unhandled exception occured while executing the unit tests");
                }
                catch
                {
                }
            }
        }
    }
}
